package com.clippick.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.Log;
import android.widget.ImageView;
import co.kr.clippick.R;

public class ImageLoader {

	MemoryCache memoryCache = new MemoryCache();
	FileCache fileCache;
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());
	ExecutorService executorService;

	int m_iOpt = 0;

	public ImageLoader(Context context) {
		fileCache = new FileCache(context);
		executorService = Executors.newFixedThreadPool(5);
	}

	public Bitmap readBitmap(String path, int iOpt) {
		m_iOpt = iOpt;
		Bitmap bitmap = memoryCache.get(path);

		if (bitmap != null) {
			Log.i("imageLoader", "bitmap is not null");
			return bitmap;
		} else {
			Log.i("imageLoader", "bitmap null");
			return getBitmap(path);
		}
	}

	// setImageBitmap 설정
	final int img_list = R.drawable.img_loading;

	public void showImage(String key_PathOrUrl, ImageView imageView, int iOpt) {
		m_iOpt = iOpt;

		imageViews.put(imageView, key_PathOrUrl);
		Bitmap bitmap = memoryCache.get(key_PathOrUrl); // 부드러운 참조로 bitmap 얻는다.

		if (bitmap != null) // 이미 map에 들어가 있으면 넣고
		{
			imageView.setImageBitmap(bitmap);
		} else // 없으면 다시 재로딩해서 넣는다.
		{
			queuePhoto(key_PathOrUrl, imageView); // 다시 재로딩해서 넣는다.

			// imageView.setImageResource(stub_id); //그전에 보여질 이미지를 세팅한다.
			imageView.setImageResource(img_list); // 그전에 보여질 이미지를 세팅한다.
		}
	}

	public void readyImage_PreAndAfter(/* String preImg_PathOrUrl, */
	final String afterImg_PathOrUrl, final int iOpt) {
		m_iOpt = iOpt;
		Thread threadImgBitmap = new Thread(new Runnable() {
			public void run() {
				setMemoryCache(afterImg_PathOrUrl);
			}
		});

		threadImgBitmap.start();
	}

	private void queuePhoto(String PathOrUrl, ImageView imageView) {
		PhotoToLoad p = new PhotoToLoad(PathOrUrl, imageView);
		executorService.submit(new PhotosLoader(p));
	}

	private Bitmap getBitmap(String url) {
		File f = fileCache.getFile(url);

		// from SD cache
		Bitmap b = decodeFile(f);
		if (b != null)
			return b;

		// from web
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			Utils.copyStream(is, os);
			os.close();
			bitmap = decodeFile(f);
			return bitmap;
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}

	// decodes image and scales it to reduce memory consumption
	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// TODO m_iOpt 동기화 필요
			Log.d("imsi", "m_iOpt : " + m_iOpt);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE;
			if (m_iOpt == 1) {
				REQUIRED_SIZE = 480;
			} else {
				REQUIRED_SIZE = 70;
			}

			int width_tmp = o.outWidth, height_tmp = o.outHeight;

			int scale = 1;

			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}

			Log.d("imsi", "\nscale : " + scale + "\no.outWidth : " + o.outWidth
					+ "\no.outHeight : " + o.outHeight + "\nREQUIRED_SIZE : "
					+ REQUIRED_SIZE);
			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;

			o2.inPreferredConfig = Bitmap.Config.RGB_565; // 16bit
			o2.inPurgeable = true;
			o2.inInputShareable = true;
			o2.inDither = false;
			o2.inTempStorage = new byte[32 * 1024];

			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);

		} catch (FileNotFoundException e) {
		}
		return null;
	}

	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		final float roundPx = pixels;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	// Task for the queue
	private class PhotoToLoad {
		public String PathOrUrl;
		public ImageView imageView;

		public PhotoToLoad(String p, ImageView i) {
			PathOrUrl = p;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;

		PhotosLoader(PhotoToLoad photoToLoad) {
			this.photoToLoad = photoToLoad;
		}

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;

			Bitmap bmp = setMemoryCache(photoToLoad.PathOrUrl);

			if (imageViewReused(photoToLoad))
				return;

			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
			Activity a = (Activity) photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	public Bitmap setMemoryCache(String PathOrUrl) {

		Bitmap bmp = memoryCache.get(PathOrUrl);

		if (bmp != null) {
			return bmp;
		}

		if (PathOrUrl.contains("http")) {
			bmp = getBitmap(PathOrUrl); // url을 통해서 bitmap얻기
		} else {
			File f = new File(PathOrUrl);
			bmp = decodeFile(f);
		}

		memoryCache.put(PathOrUrl, bmp);

		return bmp;
	}

	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.PathOrUrl))
			return true;
		return false;
	}

	// Used to display bitmap in the UI thread
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;

			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);
			else {
				photoToLoad.imageView.setImageResource(img_list);
			}
		}
	}

	public void clearCache() {
		memoryCache.clear();
		fileCache.clear();
	}

}
